/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Services;

import Entitys.Movie;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

/**
 *
 * @author Administrador
 */
public class MovieDAO {
    private static EntityManagerFactory emf= Persistence.createEntityManagerFactory("GRLPU");
    private static EntityManager em=emf.createEntityManager();
    
    public void create(Movie mov){
        em.getTransaction().begin();
        try {
            em.persist(mov);
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
    }
    
    public boolean delete(Movie mov) {

        
        em.getTransaction().begin();
        Movie m= em.find(Movie.class, mov.getId());
        boolean ret = false;
        try {
            em.remove(m);
            em.getTransaction().commit();
            ret = true;
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            em.close();
            return ret;
        }
            
    }
    
    public Movie findAMovie(String name){
        TypedQuery<Movie> q=em.createQuery("SELECT m FROM Movie m WHERE m.name LIKE :name",Movie.class);
        try {
           return q.getSingleResult();  
        } catch (Exception e) {
           e.printStackTrace(); 
        } finally {
          em.close();  
        }
        return null;
    }
    
    public List<Movie> findAllMovies(String name){
        TypedQuery<Movie> q=em.createQuery("SELECT m FROM Movie m",Movie.class);
        try {
           return q.getResultList();  
        } catch (Exception e) {
           e.printStackTrace(); 
        } finally {
          em.close();  
        }
        return null;
    }
}